<template>
  <div class="planvisit-main guanwang-bg" style="height: calc(100vh - 124px);border-radius: 10px">
    <div :style="{paddingTop:100 * (10 / screensStore.bodyHeight) + 'vh',
    paddingLeft:100 * (10 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (10 / screensStore.bodyWidth) + 'vw',
    marginBottom:100 * (10 / screensStore.bodyHeight) + 'vh'}"
         v-if="isEmpty">
      <div class="title-desp">{{screensStore.selPeriodObj.periodName}}</div>
      <div style="margin-top: 20px">
        <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
          <el-form-item>
            <el-tag
              type="primary"
              effect="dark"
              round
            >
              申诉样本列表
            </el-tag>
          </el-form-item>
          <el-form-item label="网点简称">
            <el-input v-model="searchData.outletsName" placeholder="请输入网点简称" />
          </el-form-item>
          <el-form-item label="省市区">
            <el-cascader
              :options="screensStore.proviceList"
              v-model="searchData.addressList"
              :props="{value:'label'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="切换层级">
            <el-cascader
              :options="daQuyuList"
              placeholder="请选择层级" clearable
              v-model="levelId1"
              :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchList"><el-icon><Search /></el-icon>查询</el-button>
            <el-button @click="onClearList"><el-icon><Refresh /></el-icon>重置</el-button>
<!--            <el-button type="primary" @click="onExportData"><el-icon><Promotion /></el-icon>导出</el-button>-->
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: flex-end">
        <down-table-show-sort :tablePropsArr="tablePropsArr" @throwTableProps="getTablePropsList"></down-table-show-sort>
      </div>
      <div>
        <el-table :data="tableData" border style="width: 100%" :tooltip-formatter="tableRowFormatter"
                  :header-cell-style="{ background: 'rgb(250,250,250)'}">
          <el-table-column label="序号" type="index" :index="indexMethod" width="80px" align="center" fixed="left"/>
          <template v-for="item in tablePropsArr">
            <el-table-column  :prop="item.prop" :label="item.label" align="center"
                              :key="item.prop" :width="item?.width ?  item?.width : 'auto'" v-if="item.isHidden"
                              :fixed="item?.fixed">
              <template #default="scope">
                <div v-if="item.prop == 'state'">
                  <el-tag
                    v-if="scope.row.state == '待执行'"
                    type="primary"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '执行中'"
                    type="warning"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '已完成'"
                    type="success"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '未执行'"
                    type="info"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '终审结束'"
                    type="danger"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else
                    type="info"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                </div>
                <div v-else>
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    :content="scope.row[item.prop]"
                    placement="top"
                  >
                    <div class="text-overflow">
                      {{ scope.row[item.prop] }}
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="handle" label="操作" align="center" width="180px" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="openInputDrawer(0,scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="fixed-row" style="width: 100%;justify-content: center;margin-top: 10px">
          <el-pagination background layout="sizes,prev,pager,next,jumper,total" :total="paging.total"
          @size-change="changeSize" @current-change="changeCurrent"/>
        </div>
      </div>
    </div>
    <div v-else style="width: 100%;height: 100%">
      <el-empty description="请先选择期次">
        <el-button type="primary" @click="toIssueselect">选择期次</el-button>
      </el-empty>
    </div>

    <el-drawer
      v-model="inputDrawer"
      title="网点申诉"
      size="90%"
      class="jihua-submit"
    >
      <el-form ref="refForm" :model="formData" :rules="formDataRules">
        <el-descriptions
          class="margin-top"
          :title="formData?.questionnaireName"
          :column="2"
          border
        >
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>网点编号</div>
            </template>
            {{formData?.outletsCode}}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查员编号</div>
            </template>
            {{formData?.phone}}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>地区</div>
            </template>
            {{formData?.provinceName}}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查结果</div>
            </template>
            <el-form-item prop="checkResult">
              <el-select placeholder="请选择调查结果" v-model="formData.checkResult" clearable
              :disabled="true">
                <el-option label="成功" value="成功"></el-option>
                <el-option label="不成功-关门" value="不成功-关门"></el-option>
                <el-option label="不成功-装修" value="不成功-装修"></el-option>
                <el-option label="不成功-搬迁" value="不成功-搬迁"></el-option>
                <el-option label="不成功-拆迁" value="不成功-拆迁"></el-option>
                <el-option label="不成功-找不到" value="不成功-找不到"></el-option>
                <el-option label="不成功-其他" value="不成功-其他"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>城市</div>
            </template>
            {{formData?.cityName}}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>不成功原因</div>
            </template>
            <el-form-item>
              <el-input clearable v-model="formData.failReason" :disabled="true"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店名称</div>
            </template>
            {{formData?.outletsName}}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店地址</div>
            </template>
            {{ formData?.provinceName + formData?.cityName + (formData?.areaName || '') + (formData?.address || '') }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>访店日期</div>
            </template>
            <el-form-item prop="visitTime">
              <el-date-picker
                :disabled="true"
                v-model="formData.visitTime"
                type="date"
                style="width: 100%"
                placeholder="请选择访店日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>天气情况</div>
            </template>
            <el-form-item prop="weather">
              <el-select placeholder="请选择天气情况" v-model="formData.weather" clearable
              :disabled="true">
                <el-option label="晴天" value="晴天"></el-option>
                <el-option label="多云" value="多云"></el-option>
                <el-option label="阴天" value="阴天"></el-option>
                <el-option label="下雨" value="下雨"></el-option>
                <el-option label="下雪" value="下雪"></el-option>
                <el-option label="雾霾" value="雾霾"></el-option>
                <el-option label="冰雹" value="冰雹"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>入店时间</div>
            </template>
            <el-form-item prop="enterTime">
              <el-date-picker
                v-model="formData.enterTime"
                type="datetime"
                placeholder="请选择入店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>离店时间</div>
            </template>
            <el-form-item prop="leaveTime">
              <el-date-picker
                v-model="formData.leaveTime"
                type="datetime"
                placeholder="请选择离店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>最终总得分</div>
            </template>
            <el-tag
              type="danger"
              effect="dark"
            >
              {{  formData.score || 0 }}分
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <div style="display: flex;align-items: center;margin-top: 10px">
        <el-select v-model="wenjuanMode" placeholder="请选择问卷渲染方式"
        @change="changeToggleMode" style="width: 200px">
          <el-option label="正常模式" value="normal"></el-option>
          <el-option label="表格模式" value="table"></el-option>
        </el-select>
      </div>

      <!--      渲染问卷-->
      <WuJie name="wenjuanBranchappeal" url="http://129.211.212.235:3005/"></WuJie>
      <el-dialog
        v-model="auditVisible"
        width="500"
        title="申诉"
        append-to-body
        center
        class="shensu-dia"
      >
        <el-form ref="refAuditForm" :model="auditFormData" :rules="formAuditRules" label-width="auto">
          <el-form-item label="申诉原因" prop="desp">
            <el-input clearable v-model="auditFormData.appealReason" type="textarea" autosize></el-input>
          </el-form-item>
          <el-form-item>
            <div style="width: 100%;justify-content: center" class="fixed-row">
              <el-button type="primary" @click="saveAudit">确定</el-button>
              <el-button @click="auditVisible = false">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>

      <template #footer>
        <div style="width: 100%;justify-content: space-between;background: #fff" class="fixed-row">
          <div>
            <el-button type="primary" @click="openFlow">流程查看</el-button>
          </div>
          <div>
            <el-button type="primary" @click="saveSubmit" v-if="formData.state && formData.isEnd == 1
        && (screensStore.roles.findIndex(item => item == 'wangdian') != -1)">申诉</el-button>
            <el-button @click="inputDrawer = false">返回</el-button>
          </div>
        </div>
      </template>
    </el-drawer>

    <flowview ref="refFlowview" is-type="1" audit-type="1" :visitPlanId="formData.id"></flowview>
  </div>
</template>
<script lang="ts" setup>
  import {screenStore} from '~/stores/modules/screen'
  import {onMounted,reactive,ref} from 'vue'
  import {useRoute,useRouter} from 'vue-router'
  import {getStateMentList,flowAppeal,exportDataInfo} from '~/api/statementview'
  import {setTableLocail,getTableLocail,getQuyu,getDetail,toggleMode} from '~/api/public'
  let periodId = ''
  let auditId = ''
  // let saveAs = null
  // if (isClient) {
  //   import('file-saver').then(module => {
  //     saveAs = module.saveAs
  //   }).catch(err => {
  //     console.error('Failed to load saveAs:', err)
  //   })
  // }
  const screensStore = screenStore()
  const route = useRoute()
  const router = useRouter()
  const refFlowview = ref()
  const refAuditForm = ref()
  const isEmpty = ref(false)
  const tableData = ref([{}])
  const inputDrawer = ref(false)
  const auditVisible = ref(false)
  const wenjuanMode = ref('normal')
  const daQuyuList = ref([])
  const levelId1 = ref([])
  const tablePropsArr = ref(
    [
      {
        prop: 'state',
        label: '状态',
        width: '120px',
        isHidden: true,
        fixed:'left'
      },
      {
        prop: 'outletsCode',
        label: '网点编号',
        width: 200,
        isHidden: true
      },
      {
        prop: 'outletsName',
        label: '网点简称',
        width: 200,
        isHidden: true
      },
      {
        prop: 'questionnaireName',
        label: '问卷名称',
        isHidden: true,
        width: 300
      },
      {
        prop:'provinceName',
        label:'省份',
        isHidden:true,
      },
      {
        prop:'cityName',
        label: '城市',
        isHidden:true,
      },
      {
        prop:'areaName',
        label:'区县',
        isHidden:true,
      },
      {
        prop:'address',
        label:'地址',
        isHidden:true,
        width: 300,
      },
      {
        prop:'enterTime',
        label:'入店时间',
        width: 180,
        isHidden:true,
      },
      {
        prop:'leaveTime',
        width: 180,
        label:'离店时间',
        isHidden:true,
      },
      {
        prop:'score',
        label:'样本总得分',
        width: 120,
        isHidden:true
      },
    ]
  )
  const paging = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  })
  const searchData = reactive({
    outletsName:'',
    provinceName:'',
    cityName:'',
    areaName:'',
    addressList:[]
  })
  const formData = reactive({
    periodId:''
  })
  const formDataRules = {}
  const auditFormData = reactive({
    id:'',
    appealReason:''
  })
  const formAuditRules = {
    appealReason:[{required:true,message:'请填写申诉原因',trigger:'blur'}]
  }
  onMounted(()=>{
    if (route.query.periodId) {
      isEmpty.value = true
      periodId = route.query.periodId
      getTableList()
    } else {
      isEmpty.value = false
    }

    getTableLocail('branchappeal').then(res => {
      if(res.code == 200 && res.data){
        tablePropsArr.value = JSON.parse(res.data.fieldJson)
      }
      else{
        tablePropsArr.value = [
          {
            prop: 'state',
            label: '状态',
            width: '120px',
            isHidden: true,
            fixed:'left'
          },
          {
            prop: 'outletsLevelName',
            label: '层级名称',
            width: 200,
            isHidden: true
          },
          {
            prop: 'outletsCode',
            label: '网点编号',
            width: 200,
            isHidden: true
          },
          {
            prop: 'outletsName',
            label: '网点简称',
            width: 200,
            isHidden: true
          },
          {
            prop: 'questionnaireName',
            label: '问卷名称',
            isHidden: true,
            width: 300
          },
          {
            prop: 'region',
            label: '分公司',
            width: 200,
            isHidden: true
          },
          {
            prop: 'community',
            label: '小区域',
            width: 200,
            isHidden: true
          },
          {
            prop:'provinceName',
            label:'省份',
            isHidden:true,
          },
          {
            prop:'cityName',
            label: '城市',
            isHidden:true,
          },
          {
            prop:'areaName',
            label:'区县',
            isHidden:true,
          },
          {
            prop:'address',
            label:'地址',
            isHidden:true,
            width: 300,
          },
          {
            prop:'enterTime',
            label:'入店时间',
            width: 180,
            isHidden:true,
          },
          {
            prop:'leaveTime',
            width: 180,
            label:'离店时间',
            isHidden:true,
          },
          {
            prop:'score',
            label:'样本总得分',
            width: 120,
            isHidden:true
          },
        ]
      }
    })
    getQuyu({periodId:periodId,projectId:screensStore.selProjectId}).then(res => {
      if(res.code == 200){
        daQuyuList.value = res.data
      }
      else{
        daQuyuList.value = []
      }
    })
  })

  // 去往期次选择页面
  function toIssueselect(){
    screensStore.activeHomeNav = '期次选择'
    router.replace({path:'/issueselect'})
  }
  const tableRowFormatter = (data) => {
    return `${data.cellValue}`
  }
  // 切换了问卷渲染方式
  function changeToggleMode(){
    const data = {
      json:JSON.stringify(wenjuanJson.value),
      type:wenjuanMode.value
    }
    toggleMode(data,'.jihua-submit').then(res => {
      if(res.code == 200){
        ElMessage.success('问卷模式切换成功')
        setTimeout(()=>{
          window.document.querySelector("iframe[name=wenjuanBranchappeal]").contentWindow.setWenJsonValue(JSON.parse(res.data),'yulan','yulan',screensStore.roles);
        },1000)
      }
    })
  }
  function onSearchList() {
    if(searchData.addressList.length){
      searchData.provinceName = searchData.addressList[0]
      searchData.cityName = searchData.addressList[1]
      searchData.areaName = searchData.addressList[2]
    }
    else{
      searchData.provinceName = ''
      searchData.cityName = ''
      searchData.areaName = ''
    }
    paging.currentPage = 1
    getTableList()
  }
  function onClearList() {
    Object.assign(searchData,{
      nodeName: '',
      outletsName: '',
      provinceName:'',
      cityName:'',
      areaName:'',
      addressList: []
    })
    levelId1.value = []
    paging.currentPage = 1
    getTableList()
  }
  function changeSize(val){
    paging.pageSize = val
    getTableList()
  }
  function changeCurrent(val){
    paging.currentPage = val
    getTableList()
  }
  function indexMethod(index:number){
    return (paging.currentPage - 1) * paging.pageSize + index + 1
  }

  const wenjuanJson = ref('')
  function openInputDrawer(type, row) {
    auditId = row.id
    wenjuanMode.value = 'normal'
    Object.assign(formData,{
      ...row
    })
    Object.assign(auditFormData,{
      ...row
    })
    formData.periodId = periodId
    getDetail(row.id).then(res => {
      if (res.code == 200) {
        if (res.data.id) {
          Object.assign(auditFormData,{
            ...row
          })
          Object.assign(formData, {
            ...res.data
          })
        }
        inputDrawer.value = true
        if (!res.data.questJson) {
          wenjuanJson.value = ''
        } else {
          wenjuanJson.value = JSON.parse(res.data.questJson)
        }
        // wenjuanJson.value = [JSON.stringify(wenjuanJson.value[0])]
        nextTick(()=>{
          if(window.document.querySelector("iframe[name=wenjuanBranchappeal]").contentWindow.setWenJsonValue){
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanBranchappeal]").contentWindow.setWenJsonValue(wenjuanJson.value,'yulan','yulan',screensStore.roles);
            },1000)
          }
          else{
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanBranchappeal]").contentWindow.setWenJsonValue(wenjuanJson.value,'yulan','yulan',screensStore.roles);
            },1000)
          }
        })
      }
    })
  }
  function saveSubmit() {
    auditFormData.appealReason = ''
    auditVisible.value = true
  }
  function getTableList() {
    const params = {
      ...searchData,
      periodId,
      current: paging.currentPage,
      size: paging.pageSize,
      isEnd:1
    }
    delete params.addressList
    params.levelTreeList = []
    if(levelId1.value.length){
      levelId1.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    }
    else{
      params.levelTreeList = null
    }
    getStateMentList(params).then(res => {
      if (res.code == 200) {
        tableData.value = res.data.records
        paging.total = res.data.total * 1
      } else {
        tableData.value = []
        paging.total = 0
      }
    })
  }
  async function saveAudit(){
    await refAuditForm.value.validate((bol)=>{
      if(bol){
        //todo 调取申诉接口
        flowAppeal(auditFormData).then(res => {
          if(res.code == 200){
            ElMessage({
              type:'success',
              appendTo:'.shensu-dia',
              message:'申诉成功'
            })
            setTimeout(()=>{
              auditVisible.value = false
              inputDrawer.value = false
              getTableList()
            },1000)
          }
          else{
            ElMessage({
              type:'error',
              appendTo:'.shensu-dia',
              message:res.msg || '申诉失败'
            })
          }
        })
      }
    })
  }

  function openFlow(){
    refFlowview.value.openFlowDrawer()
  }
  function onExportData(){
    const params = {
      ...searchData,
      periodId,
    }
    delete params.addressList
    exportDataInfo(periodId).then(res => {
      ElMessage.success( '网点申诉信息导出成功')
      saveAs(res,'网点申诉信息')
    })
  }

  const getTablePropsList = (tablePropsArrs) => {
    tablePropsArr.value = tablePropsArrs
    const data = {
      name:'branchappeal',
      fieldJson:JSON.stringify(tablePropsArr.value)
    }
    setTableLocail(data)
  }
</script>

<style scoped lang="less">
  .title-desp{
    font-size: 18px;
    color: #666;
    font-weight: 700;
  }
  .margin-top ::v-deep .el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell .el-form-item {
    margin-bottom: 0;
  }
</style>
